<template>
    <div class='potential'>
        <div class="container">
            <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" class="search-con">
                <el-form-item label="老人姓名" prop="key_name">
                    <el-input v-model="queryParams.key_name" placeholder="请输入" clearable size="small" />
                </el-form-item>
                <el-form-item label="性别" prop="key_sex">
                    <el-select v-model="queryParams.key_sex" placeholder="请选择" clearable size="small">
                        <el-option v-for="dict in sexList" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="key_status">
                    <el-select v-model="queryParams.key_status" placeholder="请选择" clearable size="small">
                        <el-option v-for="dict in statusList" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="注册时间：" prop="regisTime">
                    <el-date-picker v-model="queryParams.regisTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                        value-format="yyyy-MM-dd" placeholder="请选择注册时间范围" />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd()" v-hasPermi="['marketSales:admit:add']">
                        新增用户</el-button>
                    <el-button type="primary" size="mini" @click="handleCoupons()" v-hasPermi="['product:manage:add']">批量赠送优惠券</el-button>
                    <!-- <el-button type="primary" size="mini" @click="handleCouponsAll()"
                        v-hasPermi="['product:manage:add']">赠送优惠券给全部会员</el-button> -->
                        <span style="margin-left: 25px; font-size:110%;font-weight: bold;color:#30B08F;">共{{ listCount }}个</span>
                </el-col>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <el-table border v-loading="loading" :data="tableList" ref="tableList" v-tableHeight :height="tableList.length > 0 ? '900px' : '120px'">
                <el-table-column type="selection" width="55" />
                <el-table-column label="序号" align="center" prop="id" />
                <el-table-column label="头像" align="center" prop="avatar">
                    <template slot-scope="scope">
                        <div v-if="scope.row.avatar" class="img-list">
                            <el-image style="width: 50px; height: 50px;border:1px solid #eee;border-radius: 50%;" :src="scope.row.avatar"
                                :preview-src-list="[scope.row.avatar]">
                            </el-image>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="用户名" align="center" prop="name" />
                <el-table-column label="登录账号" align="center" prop="nicename" />
                <el-table-column label="手机号" align="center" prop="mobile" />
                <el-table-column label="性别" align="center" width="80">
                    <template slot-scope="scope">
                        <span v-if="scope.row.sex == 0">{{ selectDictLabel(sexList, scope.row.sex) }}</span>
                        <el-tag v-else :type="scope.row.sex == 1 ? 'danger' : ''">
                            {{ selectDictLabel(sexList, scope.row.sex) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="推荐码" align="center" prop="invite_code" />
                <el-table-column label="状态" align="center" prop="status">
                    <template #default="scope">
                        <el-tag :type="scope.row.status == 2
                                ? 'success'
                                : scope.row.status == 1
                                    ? 'danger'
                                    : ''
                            ">{{
                            selectDictLabel(statusList, scope.row.status) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="注册时间" align="center" prop="regis_time" width="130" />
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button v-if="scope.row.status != 2" size="mini" type="text" icon="el-icon-edit" @click="handleEdit(JSON.parse(JSON.stringify(scope.row)))"
                            v-hasPermi="['marketSales:admit:edit']">
                            编辑
                        </el-button>
                        <el-button v-if="scope.row.status != 2" size="mini" type="text" icon="el-icon-edit" @click="title = '紧急联系人'; userId = String(scope.row.id); handleShow = 'contact'"
                            v-hasPermi="['marketSales:admit:edit']">
                            紧急联系人
                        </el-button>
                        <el-button size="mini" type="text" @click="handleCoupon(scope.row)" v-hasPermi="['product:manage:unRacking']">赠送优惠券
                        </el-button>
                        <el-button size="mini" type="text" @click="title = '修改登录密码'; userId = String(scope.row.id); handleShow = 'change'" v-hasPermi="['user:staff:edit']">
                            修改密码
                        </el-button>
                        <el-button v-if="scope.row.status == 0" size="mini" type="text" @click="handleAble(scope.row)" v-hasPermi="['user:staff:stop']">停用
                        </el-button>
                        <el-button v-if="scope.row.status == 1" size="mini" type="text" @click="handleAble(scope.row)" v-hasPermi="['user:staff:start']">启用
                        </el-button>
                        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">
                            删除</el-button>

                        <el-button size="mini" type="text" @click="handleBalance(scope.row)">余额记录
                        </el-button>
                        <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="getSuperLists(scope.row)">
                            指定上级</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="pageCount > 0" :pageCount="pageCount" :page.sync="queryParams.page" :limit.sync="queryParams.limit" @pagination="getList" />
        </div>
        <!-- 新增老人 -->
        <add v-if="handleShow == 'add' || handleShow == 'edit'" :title="title" :handleShow="handleShow" :data="curRow" @close="handleShow = ''" @load="getList" />
        <emergency v-if="handleShow == 'contact'" :title="title" :handleShow="handleShow" :userId="userId" @close="userId = null; handleShow = ''"
            @load="getList" />
        <change v-if="handleShow == 'change'" :title="title" :handleShow="handleShow" :userId="userId" @close="userId = null; handleShow = ''" @load="getList" />
        <balanceRecord v-if="handleShow == 'balanceRecord'" :uid="String(uid)" @close="uid='';handleShow = ''" />

        <el-dialog title="赠送优惠券" visible v-if="handleShow == 'assign'" @close="close()" width="65%" append-to-body :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="100px" v-loading="formLoading">
                <el-form-item prop="coupon_id" label="赠送优惠券">
                    <el-select v-model="coupon_ids" placeholder="请选择优惠券" clearable size="small" multiple>
                        <el-option v-for="dict in couponList" :key="dict.id" :label="dict.title" :value="dict.id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="close()">取 消</el-button>
                <el-button type="primary" @click="submit" :disabled="formLoading">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>
<script>
import throttle from 'lodash.throttle'
import emergency from "./handle/emergency"
import add from "./handle/add"
import change from "./handle/change"
import balanceRecord from "./handle/balanceRecord.vue"
import { getUsersLists, getUsersInfo, delUsersInfo, setUsersStatus, getGivenCouponsLists, setGiveCoupons, getHigherListsAll } from "@/api/senior/user.js"
import { departStatus, seX } from "@/api/dictionary"
export default {
    name: 'potential',
    props: {
    },
    components: {
        add,
        emergency,
        change,
        balanceRecord
    },
    data() {
        return {
            showSearch: true,
            loading: false,
            total: 0,
            pageCount: 0,
            sexList: seX,
            queryParams: {
                page: 1,
                limit: 20,
                key_name: null,
                key_sex: null,
                key_status: null,
                regisTime: [],
            },
            tableList: [],
            handleShow: "",
            curRow: {},
            formLoading: false,
            title: "",
            statusList: departStatus,
            userId: null,
            name: null,
            title: "",
            codeList: [],
            form: {
                uids: '',
                couponids: '',
            },
            coupon_ids: [],
            rules: {
                busin_id: [{ required: true, message: '请选择优惠券', trigger: 'change' }],
            },
            couponList: [],
            uid: '',
            listCount:'',
        }
    },
    created() {
        this.getList()
    },
    methods: {
        getList() {
            this.loading = true;
            this.queryParams.key_regis_time_start = this.queryParams.regisTime.length > 0 ? this.queryParams.regisTime[0] : null
            this.queryParams.key_regis_time_end = this.queryParams.regisTime.length > 0 ? this.queryParams.regisTime[1] : null
            getUsersLists(this.queryParams).then(res => {
                this.tableList = res.data ? res.data.lists : [];
                this.pageCount = res.data.pageCount;
                this.listCount = res.data.listsCount;
                this.loading = false;
            });
        },
        handleQuery() {
            this.queryParams.page = 1;
            this.getList();
        },
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // handleSizeChange(val) {
        //     this.queryParams.limit = val;
        //     this.getList()
        // },
        close() {
            this.curRow = {}
            this.form = {}
            this.handleShow = ""
        },
        handleAdd() {
            this.curRow = {};
            this.title = '新增';
            this.handleShow = 'add'
        },
        handleEdit(row) {
            // this.form.uid = row.id;
            getUsersInfo({ uid: row.id }).then(res => {
                // this.form = { ...this.form, ...res.data }
                this.curRow = res.data
                this.title = '编辑';
                this.handleShow = 'edit'
            })
        },
        handleAble(row) {
            let label = row.status == 0 ? '停用' : '启用';
            this.$confirm(`是否将“${row.name}”${label}?`, "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return setUsersStatus({ uid: row.id });
            }).then(() => {
                this.getList();
                this.msgSuccess(`${label}成功`);
            })
        },
        handleBalance(row) {
            this.uid = row.id
            this.handleShow = 'balanceRecord'

        },
        handleDelete(row) {
            this.$confirm('是否确认删除' + '"' + row.name + '"' + '?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delUsersInfo({ uid: row.id });
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            })
        },
        toggleSelection(row) {
            this.$refs.tableList.toggleRowSelection(row);
        },
        getCouponLists() {
            getGivenCouponsLists().then(res => {
                this.couponList = res.data;
                console.log(this.couponList, '优惠券列表')
            })
        },
        getSuperLists(row) {
            getHigherListsAll({ uid: row.id }).then(res => {
                this.couponList = res.data;
                console.log(this.couponList, '优惠券列表')
            })
        },
        // 多选框选中数据
        handleCoupons(selection) {
            this.coupon_ids = [];
            this.selectData = this.$refs.tableList.selection;
            console.log(this.selectData, 'xuanzhongdata')
            if (this.selectData.length == 0) {
                this.$confirm('请选择用户进行批量操作', "警告", {
                    confirmButtonText: "确定",
                    type: "warning"
                })
            } else if (this.selectData.length > 0) {
                for (let i = 0; i < this.selectData.length; i++) {
                    let codes = this.selectData[i].id
                    this.codeList.push(codes)
                    console.log(this.codeList, 'codes')
                }
                this.handleShow = 'assign';
                // this.getBusinLists();
                this.form.uids = this.codeList.join(",")
            }
        },

        handleCoupon(row) {
            this.handleShow = 'assign';
            this.getCouponLists();
            this.form.uids = row.id;
            this.coupon_ids = [];
        },

        // handleCouponsAll(){
        //     this.handleShow = 'assign';
        //     this.getCouponLists();
        //     this.form.uids = '';
        //     this.coupon_ids = [];
        // },
        submit: throttle(function () {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.formLoading = true;
                    this.form.couponids = this.coupon_ids ? this.coupon_ids.join(",") : null
                    setGiveCoupons(this.form).then(res => {
                        this.msgSuccess("操作成功！");
                        this.close()
                        this.formLoading = false;
                        this.getList();
                    }).catch(() => {
                        this.formLoading = false;
                    })
                }
            })
        }, 1000, { trailing: false }),
    }
}
</script>

<style lang='scss' scoped></style>
